package FileOperation;

import Book.*;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class saveBooks {
    public void fileSaveCover(Bookshelf books) throws SQLException {
        // 先删掉之前的数据
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_mysql6?characterEncoding=utf8&&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        // 2.建立连接
        Connection connection = dataSource.getConnection();
        String sql2 = "delete from bookshelf";
        PreparedStatement statement = connection.prepareStatement(sql2);
        statement.executeUpdate();
        statement.close();
        connection.close();

        for (int i = 0; i < books.getBooksNumber(); i++) {
            Book book = books.getBooks(i);
            DataSource dataSource1 = new MysqlDataSource();
            ((MysqlDataSource) dataSource1).setURL("jdbc:mysql://127.0.0.1:3306/java_mysql6?characterEncoding=utf8&&useSSL=false");
            ((MysqlDataSource) dataSource1).setUser("root");
            ((MysqlDataSource) dataSource1).setPassword("123456");
            // 2.建立连接
            Connection connection1 = dataSource1.getConnection();
            // 3.建立sql语句
            String sql1 = "insert into bookshelf values (?,?,?,?,?)";
            // 4.解析sql并执行
            PreparedStatement statement1 = connection1.prepareStatement(sql1);
            statement1.setString(1, book.getName());
            statement1.setString(2, book.getAuthor());
            statement1.setDouble(3, book.getPrice());
            statement1.setString(4, book.getType());
            statement1.setString(5, book.getIsBorrow());
            int ret = statement1.executeUpdate();

            statement1.close();
            connection1.close();
        }
    }
}
